package com.lost.octopus.es.processor.scheduler;

import com.alibaba.ttl.TtlCallable;
import com.lost.octopus.es.processor.dao.mapper.mybatis.BaseAsyncMapper;
import com.lost.octopus.es.processor.entity.IdEntity;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 增量/全量更新基础的异步服务工具
 * 条件：
 * <br>
 * 0.指定存储的实体
 * 1.需要实现 {@link BaseAsyncMapper} 方法获取数据ID范围和数据对象
 * 2.需要操作该对象的 {@link ElasticsearchRepository}esDao
 * 3. ID类型，需要可比较，可排序（数据库性能高）
 * @author zhangbh
 **/
@Log4j2
@Component
public class EsAsyncManagement {

    @Resource(name = "asyncFindWillSyncInfo")
    private ThreadPoolTaskExecutor taskExecutor;

    public <T extends IdEntity<ID>, ID> Future<List<T>> asyncFindWillSyncInfo(List<Integer> burstIds, EsSyncIndexOperator<T, ID, ?, ?> operator) {
        // 使用阿里的TTL工具，将线程变量传递到子线程中
        return taskExecutor.submit(TtlCallable.get(() -> {
            List<T> records = operator.findWillSyncInfo(burstIds);
            log.debug("当前块的数据查询结束\n查询的id= {}", burstIds);
            return records;
        }));
    }
}
